from whiff.middleware import misc
from whiff import resolver
from whiff import whiffenv
from whiff.middleware import setInnerHtml
#import pprint # for debug
from whiff.rdjson import jsonParse

class changeCanvasCallback(misc.utility):
    def __call__(self, env, start_response):
        env = resolver.process_cgi(env, parse_cgi=True)
        cgiDict = env[whiffenv.CGI_DICTIONARY]
        #testjs = "alert(%s);" % repr(p#pr.pformat(cgiDict))
        ##pr "testjs"
        ##pr testjs
        #pr cgiDict
        #pr pprint.pformat(cgiDict)
        name = whiffenv.cgiGet(env, "descriptionSetNameBefore", "").strip()
        newname = whiffenv.cgiGet(env, "descriptionSetNameAfter", "").strip()
        review = whiffenv.cgiGet(env, "review", "").strip()
        dataString = whiffenv.cgiGet(env, "schema", "{}").strip()
        dataString = resolver.unquote(dataString)
        schemaData = self.param_json(dataString, env)
        # edit the schema data
        if not name:
            if not newname:
                # xxxx error message!
                pass
            else:
                # xxxx new description set
                newattributes = []
                newDescription = self.getAttributeDescription(env, "")
                if newDescription:
                    newattributes.append(newDescription)
                newname = newname.strip()
                if newname:
                    schemaData[newname] = newattributes
        else:
            # modify existing description set
            attributes = schemaData[name]
            newattributes = []
            for attr in attributes:
                oldname = attr["name"]
                newDescription = self.getAttributeDescription(env, oldname)
                if newDescription:
                    newattributes.append(newDescription)
            # look for new attribute
            newDescription = self.getAttributeDescription(env, "")
            if newDescription:
                newattributes.append(newDescription)
            del schemaData[name]
            newname = newname.strip()
            if newname:
                schemaData[newname] = newattributes
        # save and load the schema data
        schemaJson = jsonParse.format(schemaData)
        #pr "new json"
        #pr schemaJson
        target = "schemaData"
        application = setInnerHtml.__middleware__(page=schemaJson, elementName=target)
        setHtml = self.param_value(application, env)
        tailAction = DODRAW
        #pr "review", review
        if review:
            tailAction = DOREVIEW % newname
        start_response("200 OK", [('Content-Type', 'application/javascript')])
        return [setHtml, tailAction]
    def getAttributeDescription(self, env, name):
        descr = {}
        newname = descr["name"] = whiffenv.cgiGet(env, "attributeName_"+name, "")
        newtypeName = descr["typeName"] = whiffenv.cgiGet(env, "attributeKind_"+name, "")
        descr["isIdentifier"] = (whiffenv.cgiGet(env, "attributeIsIdentifier_"+name, None) is not None)
        descr["isMandatory"] = (whiffenv.cgiGet(env, "attributeIsMandatory_"+name, None) is not None)
        descr["isOnto"] = (whiffenv.cgiGet(env, "attributeIsOnto_"+name, None) is not None)
        descr["isOneToOne"] = (whiffenv.cgiGet(env, "attributeIsOneToOne_"+name, None) is not None)
        descr["isMultiple"] = (whiffenv.cgiGet(env, "attributeIsMultiple_"+name, None) is not None)
        #pr name, "becomes", descr
        if newname and newtypeName:
            return descr
        else:
            return None

DODRAW = """
closePrompt();
//alert("now redrawing schema");
drawSchemaFromData();
"""

DOREVIEW = """
showEditDialogue("%s");
"""

__middleware__ = changeCanvasCallback
